package com.spzx.common.rabbit.service;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送延迟消息
     *
     * @param exchange   交换机名称
     * @param routingKey 路由名称
     * @param msg        消息
     * @param delayTime  延迟时间
     */
    public void sendDelayMessage(String exchange, String routingKey, Object msg, int delayTime) {

        // 消息对象
        GuiguCorrelationData correlationData = new GuiguCorrelationData();
        String id = "mq:" + UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(id);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setMessage(msg);
        correlationData.setDelay(true);
        correlationData.setDelayTime(delayTime);

        // 发送消息
        rabbitTemplate.convertAndSend(exchange,
                routingKey,
                msg,
                message -> {
                    message.getMessageProperties().setDelay(delayTime * 1000);
                    return message;
                },
                correlationData);
        // 保存消息到redis--这里在消息的return机制时应用
        redisTemplate.opsForValue().set(id, JSON.toJSONString(correlationData), 10, TimeUnit.MINUTES);
    }

    /**
     * 发送消息
     * @param exchange 交换机
     * @param routingKey 路由键
     * @param msg 消息
     */
    public void sendMessage(String exchange, String routingKey, String msg) {

        GuiguCorrelationData correlationData = new GuiguCorrelationData();
        String id = "mq:" + UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(id);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setMessage(msg);
        // 发送消息
        rabbitTemplate.convertAndSend(exchange, routingKey, msg);

        // 保存消息到redis--这里在消息的return机制时应用
        redisTemplate.opsForValue().set(id, JSON.toJSONString(correlationData), 10, TimeUnit.MINUTES);
    }

}